import { verifyAccessToken } from '~/utils/jwt-utils';
import { unAuthorizedResponse, useResponseSuccess, customResponse } from '~/utils/response';
import { queryDatabase } from '~/functions';

// 日期格式化

export default eventHandler(async (event) => {
  const userinfo = verifyAccessToken(event);
  if (!userinfo) {
    return unAuthorizedResponse(event);
  }

  try {
    // 读取请求体
    const { action, orderNo, data } = await readBody(event);

    // 处理 SUBMIT 请求
    if (action === 'submit') {
      if (!orderNo) throw new Error('委托单编号不能为空！');
      if (!data) throw new Error('提交的数据为空！');

      const parsedData = JSON.parse(data);
      // 处理JSON类型字段
      const jsonFields = ['sampleProp', 'testItems'];
      const processData = Object.entries(parsedData).reduce((acc, [key, value]) => {
        acc[key] = jsonFields.includes(key) ? JSON.stringify(value) : value;
        return acc;
      }, {} as Record<string, any>);
      // 插入数据库（假设表结构包含所有字段）
      const fields = Object.keys(processData).join(', ');
      const placeholders = Object.keys(processData)
        .map(() => '?')
        .join(', ');
      const queryString = `INSERT INTO testorder (orderNo, ${fields}) VALUES (?, ${placeholders})
                    ON DUPLICATE KEY UPDATE ${Object.keys(processData)
                      .map((k) => `${k}=VALUES(${k})`)
                      .join(', ')}`;

      await queryDatabase(queryString, [orderNo, ...Object.values(processData)]);

      // // 生成样品台账
      // const orderColumns = [
      //   'clientName',
      //   'contactPerson',
      //   'orderNo',
      //   'sampleName',
      //   'modelSpec',
      //   'quantity',
      //   'testItems',
      //   'sampleHandling',
      // ];
      // // 从processData中提取需要的字段
      // const orderData = orderColumns.reduce((acc, key) => {
      //   acc[key] = processData[key];
      //   return acc;
      // }, {} as Record<string, any>);
      // orderData.orderNo = orderNo;
      // orderData.createTime = formatDateTime(new Date(), 'date');
      // orderData.updateTime = formatDateTime(new Date(), 'dateTime');

      // const sampleQuantity = parseInt(orderData.quantity.replace(/[^0-9]/g, ''), 10); // 提取数字部分并转换为整数
      // const col = Object.keys(orderData).join(', ');
      // const value = Object.keys(orderData)
      //   .map(() => '?')
      //   .join(', ');
      // let sampleNo = '';
      // for (let i = 0; i < sampleQuantity; i++) {
      //   sampleNo = 'ZW-' + formatDateTime(new Date(), 'timestamp') + '-' + (i + 1).toString().padStart(3, '0'); // 生成样品编号
      //   const queryString = `INSERT INTO samplelists (sampleNo, ${col}) VALUES (?, ${value})`;
      //   await queryDatabase(queryString, [sampleNo, ...Object.values(orderData)]);
      // }

      return useResponseSuccess('提交成功！');
    } else if (action === 'getInfo') {
      // 处理 GETINFO 请求
      let queryString;
      const args = [];

      if (!orderNo && data) {
        // 判断data是否为"xxxx-xx-xx"格式
        const regex = /^\d{4}-\d{2}-\d{2}$/;
        if (!regex.test(data)) throw new Error('日期格式不正确！');

        // 解析年和月
        const [year, month] = data.split('-').map(Number);

        // 当月第一天
        const startDate = year + '-' + month.toString().padStart(2, '0') + '-01';
        // 计算当月最后一天
        const endDate = data;

        // 根据 data 参数传递的日期查询出orderDate介于对应的月份下的最大orderNo
        queryString = `SELECT orderNo FROM testorder WHERE orderDate BETWEEN ? AND ? ORDER BY orderNo DESC LIMIT 1`;
        args.push(startDate, endDate);
      } else if (!orderNo && !data) {
        // 查询所有数据
        queryString = `SELECT * FROM testorder`;
      } else if (orderNo) {
        // 根据 orderNo 查询数据
        queryString = `SELECT * FROM testorder WHERE orderNo = ?`;
        args.push(orderNo);
      }

      const results = <any[]>await queryDatabase(queryString, args);

      if (!orderNo && data) {
        let res;
        if (results.length === 0) {
          res = '001';
        } else if (results.length > 0) {
          res = (parseInt(results[0].orderNo.split('-').pop(), 10) + 1).toString().padStart(3, '0');
        }
        const [year, month] = data.split('-').map(Number);
        res = year + month.toString().padStart(2, '0') + '-' + res;
        return useResponseSuccess('RT/JC-WT-' + res);
      } else {
        if (results.length === 0) {
          throw new Error(orderNo ? `数据库中无编号为：${orderNo}！的数据！` : '未获取到任何信息！');
        } else {
          return useResponseSuccess(results);
        }
      }
    }
  } catch (error) {
    return customResponse(-2, error.message);
  }
});
